<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import loader from '@monaco-editor/loader'

const editorContainer = ref(null)
const editor = ref(null)
const currentLanguage = ref('javascript')
const currentTheme = ref('vs-dark')

const languages = [
  'javascript',
  'typescript',
  'html',
  'css',
  'json',
  'python',
  'java',
  'cpp',
  'sql',
  'markdown'
]

const themes = [
  { id: 'vs', name: '浅色' },
  { id: 'vs-dark', name: '深色' },
  { id: 'hc-black', name: '高对比度' }
]

// 示例代码
const sampleCode = {
  javascript: `// 示例代码
function greeting(name) {
    return \`Hello, \${name}!\`;
}

console.log(greeting('World'));`,
  python: `# 示例代码
def greeting(name):
    return f"Hello, {name}!"

print(greeting("World"))`,
  sql: `-- 示例查询
SELECT 
    users.name,
    COUNT(orders.id) as order_count
FROM users
LEFT JOIN orders ON users.id = orders.user_id
GROUP BY users.id
HAVING order_count > 0
ORDER BY order_count DESC;`
}

// 初始化编辑器
const initializeEditor = async () => {
  try {
    const monaco = await loader.init()
    
    editor.value = monaco.editor.create(editorContainer.value, {
      value: sampleCode[currentLanguage.value],
      language: currentLanguage.value,
      theme: currentTheme.value,
      automaticLayout: true,
      minimap: { enabled: true },
      fontSize: 14,
      lineNumbers: 'on',
      roundedSelection: false,
      scrollBeyondLastLine: false,
      readOnly: false,
      cursorStyle: 'line',
      tabSize: 2,
      wordWrap: 'on',
      formatOnPaste: true,
      formatOnType: true,
    })

    // 添加快捷键
    editor.value.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
      saveCode()
    })
  } catch (error) {
    console.error('Failed to initialize editor:', error)
  }
}

// 更改语言
const changeLanguage = (lang) => {
  if (!editor.value) return
  
  const monaco = window.monaco
  const model = editor.value.getModel()
  monaco.editor.setModelLanguage(model, lang)
  currentLanguage.value = lang
  
  // 如果有示例代码，则更新内容
  if (sampleCode[lang]) {
    editor.value.setValue(sampleCode[lang])
  }
}

// 更改主题
const changeTheme = (theme) => {
  if (!editor.value) return
  
  const monaco = window.monaco
  monaco.editor.setTheme(theme)
  currentTheme.value = theme
}

// 保存代码
const saveCode = () => {
  if (!editor.value) return
  
  const code = editor.value.getValue()
  const blob = new Blob([code], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `code.${currentLanguage.value}`
  link.click()
  URL.revokeObjectURL(url)
}

// 格式化代码
const formatCode = () => {
  if (!editor.value) return
  
  editor.value.getAction('editor.action.formatDocument').run()
}

onMounted(() => {
  initializeEditor()
})

onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.dispose()
  }
})
</script>

<template>
  <div class="editor-container">
    <div class="toolbar">
      <div class="toolbar-group">
        <label>语言：</label>
        <select v-model="currentLanguage" @change="changeLanguage($event.target.value)">
          <option v-for="lang in languages" :key="lang" :value="lang">
            {{ lang }}
          </option>
        </select>
      </div>

      <div class="toolbar-group">
        <label>主题：</label>
        <select v-model="currentTheme" @change="changeTheme($event.target.value)">
          <option v-for="theme in themes" :key="theme.id" :value="theme.id">
            {{ theme.name }}
          </option>
        </select>
      </div>

      <div class="toolbar-group">
        <button @click="formatCode">格式化代码</button>
        <button @click="saveCode">保存文件</button>
      </div>
    </div>

    <div ref="editorContainer" class="monaco-editor"></div>
  </div>
</template>

<style scoped>
.editor-container {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.toolbar {
  display: flex;
  gap: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 10px;
}

.toolbar-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
}

button {
  padding: 6px 12px;
  background-color: #007acc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #005999;
}

.monaco-editor {
  flex-grow: 1;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style> 